package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.MySocket;
import com.dotstone.chipism.bean.MySocket.RecDataCallBackListener_TempHumity;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.util.ConvertUtil;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.KeyManager;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;
import com.tiqiaa.ircode.impl.InfraredFetcher;
import com.tiqiaa.irdnasdk.IrDnaSdkHelper;
import com.tiqiaa.remote.IRemoteManager;
import com.tiqiaa.remote.entity.AirRemoteState;
import com.tiqiaa.remote.entity.AirTemp;
import com.tiqiaa.remote.entity.Infrared;
import com.tiqiaa.remote.entity.Key;
import com.tiqiaa.remote.entity.Remote;
import com.tiqiaa.remote.impl.RemoteManager;

import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
//import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class AddAirActivity extends BaseActivity {

	private LinearLayout mBackL;
	private TextView mStatusBar;
	private Button mPowerB;
	private TextView mTitleTv;
	private boolean power = true;
	private Button mVoiceB;
	private Button mModeB;
	private Button mWindB;
	private Button mDerictionB;
	private Button mDerictionB1;
	private Button mWarmB;
	private Button mColdB;
	private Button mTimeB;
	private Button mMoreB;
	private RelativeLayout mF;
	private RelativeLayout mS;
	private float current_degree;
	private int tempX1;
	private int tempY1;
	// private int o_x = 306;
	// private int o_y = 308;
	private int o_x = 300;
	private int o_y = 302;
	private static int dpi;
	private int temp;
	private int temp1;
	private long lastTime;
	private long currentTime;
	/**
	 * 手机震动模块
	 */
	private Vibrator vibrator;
	private ImageView mShiImg;
	private ImageView mGeImg;
	private ImageView mModeImg;
	private int mode = 0; // 0 制冷 1 制暖 2 干燥
	private MySocket socket;
	private int inner;
	private Button mSaveB;
	private int type;
	private String aplliance;
	private String brand;
	private String model;
	private String remoteId;
	private List<Key> keys = new ArrayList<Key>();
	private List<com.dotstone.chipism.bean.Key> localKeys = new ArrayList<com.dotstone.chipism.bean.Key>();
	private List<com.dotstone.chipism.bean.Key> moreKeys = new ArrayList<com.dotstone.chipism.bean.Key>();
	private List<com.dotstone.chipism.bean.Key> tempKeys = new ArrayList<com.dotstone.chipism.bean.Key>();
	private List<Button> buttons = new ArrayList<Button>();
	private HashMap<Integer, String> cmdMaps = new HashMap<Integer, String>();
	private HashMap<Integer, String> irDataMaps = new HashMap<Integer, String>();
	private Remote remote;
	private SVProgressHUD mSVProgressHUD;
	private Dialog dialog;
	private GridView mKeysG;
	private KeyAdapter mAdapter;
	private AirRemoteState mState;
	private InfraredFetcher fetcher;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;
		case R.id.power_b:
			// 800 4000
			if (power) { // 当前打开 发送关指令
				mPowerB.setBackgroundResource(R.drawable.kaiguan22x);
				if (cmdMaps.get(4000) == null || cmdMaps.get(4000) == "") {
					sendCmd(cmdMaps.get(800));
					Log.i("wmy",
							keys.get(0).getName() + " " + keys.get(0).getLocalName() + " " + keys.get(0).getRemarks());
				} else {
					sendCmd(cmdMaps.get(4000));
				}

				resetButton(false);
			} else { // 当前关闭 发送开的指令
				mPowerB.setBackgroundResource(R.drawable.kaiguan12x);
				sendCmd(cmdMaps.get(800));
				resetButton(true);
			}
			power = !power;
			vibrator.vibrate(50);
			break;
		case R.id.voice_btn:
			ToastShow.Show(getApplicationContext(), "尚未实现");
			break;
		case R.id.mode_btn:
			// 832
			if (mode == 0) {
				mode = 1;
				mModeImg.setImageResource(R.drawable.hot);
			} else if (mode == 1) {
				mode = 2;
				mModeImg.setImageResource(R.drawable.dry);
			} else {
				mode = 0;
				mModeImg.setImageResource(R.drawable.cold);
			}
			sendCmd(cmdMaps.get(832));
			vibrator.vibrate(50);
			break;
		case R.id.wind_speed_btn:
			// 833
			sendCmd(cmdMaps.get(833));
			vibrator.vibrate(50);
			break;
		case R.id.wind_deriction_btn:
			// 834 左右扫风
			sendCmd(cmdMaps.get(834));
			vibrator.vibrate(50);
			break;
		case R.id.wind_deriction_btn1:
			// 835 上下扫风
			sendCmd(cmdMaps.get(835));
			vibrator.vibrate(50);
			break;
		case R.id.warn_btn:
			// 883
			sendCmd(cmdMaps.get(883));
			mModeImg.setImageResource(R.drawable.hot);
			vibrator.vibrate(50);
			break;
		case R.id.cold_btn:
			// 882
			sendCmd(cmdMaps.get(882));
			mModeImg.setImageResource(R.drawable.cold);
			vibrator.vibrate(50);
			break;
		case R.id.time_btn:
			// 876
			sendCmd(cmdMaps.get(876));
			vibrator.vibrate(50);
			break;
		case R.id.more_btn:
			// ToastShow.Show(getApplicationContext(), "无更多按键");
			initDialog();
			break;
		case R.id.nextstep:
			save();
			break;
		default:
			break;
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				int[] temps = new int[2];
				temps = Util.getTempRes(msg.arg1);
				mShiImg.setImageResource(temps[0]);
				mGeImg.setImageResource(temps[1]);
				if (msg.arg2 == 0) {
					mModeImg.setImageResource(R.drawable.auto);
				} else if (msg.arg2 == 1) {
					mModeImg.setImageResource(R.drawable.hot);
				} else if (msg.arg2 == 2) {
					mModeImg.setImageResource(R.drawable.cold);
				} else if (msg.arg2 == 3) {
					mModeImg.setImageResource(R.drawable.dry);
				}
				break;

			default:
				break;
			}
		}
	};

	private void initDialog() {
		// TODO Auto-generated method stub
		dialog = new Dialog(AddAirActivity.this, R.style.MyDialogStyle);
		dialog.setContentView(R.layout.dialog_more_key);
		Window dialogWindow = dialog.getWindow();
		mKeysG = (GridView) dialog.findViewById(R.id.key_gv);
		mAdapter = new KeyAdapter();
		mKeysG.setAdapter(mAdapter);
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.setGravity(Gravity.CENTER);
		lp.width = LayoutParams.FILL_PARENT;
		dialogWindow.setAttributes(lp);
		dialog.show();
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_air;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		dpi = DeviceManager.getInstance().getDEVICE_DENSITY_DPI();
		o_x = 309 * dpi / 320;
		o_y = 309 * dpi / 320;
		mBackL = $(R.id.back_layout);
		mStatusBar = $(R.id.tv_statusBar_mian);
		mTitleTv = $(R.id.title_tv);
		mPowerB = $(R.id.power_b);
		mVoiceB = $(R.id.voice_btn);
		mModeB = $(R.id.mode_btn);
		mWindB = $(R.id.wind_speed_btn);
		mDerictionB = $(R.id.wind_deriction_btn);
		mDerictionB1 = $(R.id.wind_deriction_btn1);
		mWarmB = $(R.id.warn_btn);
		mColdB = $(R.id.cold_btn);
		mTimeB = $(R.id.time_btn);
		mMoreB = $(R.id.more_btn);
		mShiImg = $(R.id.shi_img);
		mGeImg = $(R.id.ge_img);
		mModeImg = $(R.id.mode_img);
		mF = (RelativeLayout) findViewById(R.id.rl_father);
		mS = (RelativeLayout) findViewById(R.id.rl_mezi);
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		lastTime = System.currentTimeMillis();
		currentTime = System.currentTimeMillis();
		mSaveB = $(R.id.nextstep);
		mSaveB.setText(getString(R.string.save));
		type = getIntent().getIntExtra("type", 999);
		aplliance = getIntent().getStringExtra("appliance");
		brand = getIntent().getStringExtra("brand");
		model = getIntent().getStringExtra("model");
		remoteId = getIntent().getStringExtra("remoteId");
		mTitleTv.setText(aplliance + " " + brand + " " + model);
		socket = SocketManager.getInstance().sMap.get(DeviceManager.getInstance().getmWlanId());
		if (socket == null) {
			ToastShow.Show(getApplicationContext(), "请重新选择网关再添加！");
			// return;
			finish();
		}
		mSaveB.setVisibility(View.VISIBLE);
		IRemoteManager manager = new RemoteManager();
		remote = manager.getRemoteByID(remoteId);
		initState();
		initKey();
		boolVersion();
		mBackL.setOnClickListener(this);
		mPowerB.setOnClickListener(this);
		mVoiceB.setOnClickListener(this);
		mModeB.setOnClickListener(this);
		mWindB.setOnClickListener(this);
		mDerictionB.setOnClickListener(this);
		mDerictionB1.setOnClickListener(this);
		mWarmB.setOnClickListener(this);
		mColdB.setOnClickListener(this);
		mTimeB.setOnClickListener(this);
		mMoreB.setOnClickListener(this);
		mSaveB.setOnClickListener(this);
		socket = SocketManager.getInstance().sMap.get(DeviceManager.getInstance().getmWlanId());
		if (socket != null) {
			setRecall();
			// initTemp();
		}
		mF.setOnTouchListener(new OnTouchListener() {
			// 根据角度 判断区域属于哪一个温度
			// 如果属于同一个温度 则不做处理
			// 如果属于不同温度 则赋值当前温度
			// 震动
			@Override
			public boolean onTouch(View v, MotionEvent e) {
				// TODO Auto-generated method stub
				int action = e.getAction();
				switch (action) {
				case MotionEvent.ACTION_DOWN:

					break;
				case MotionEvent.ACTION_MOVE:
					// Log.i("wmy", "拖动" + e.getX() + " " + e.getY());
					if (adjustArea(o_x, o_y, e.getX(), e.getY())) {
						current_degree = detaDegree(o_x, o_y, e.getX(), e.getY());
						// 根据象限求坐标
						if (current_degree < 50 || current_degree > 130) {
							// if (currentTime - lastTime > 150) {
							// lastTime = currentTime;
							// adjustTemp(current_degree);
							// }
							getButtonXY(current_degree);
							mS.setX(tempX1 - 24 * dpi / 320);
							mS.setY(tempY1 - 24 * dpi / 320);
							mS.postInvalidate();
						}
					} else {
						return false;
					}
					break;
				case MotionEvent.ACTION_UP:
					// Log.i("wmy", "上提" + e.getX() + " " + e.getY());
					if (adjustArea(o_x, o_y, e.getX(), e.getY())) {
						current_degree = detaDegree(o_x, o_y, e.getX(), e.getY());
						// 根据象限求坐标
						if (current_degree < 50 || current_degree > 130) {
							Log.i("wmy", "当前上提角度" + current_degree);
							adjustTemp(current_degree);
							getButtonXY(current_degree);
							mS.setX(tempX1 - 20 * dpi / 320);
							mS.setY(tempY1 - 20 * dpi / 320);
							mS.postInvalidate();
						}
					} else {
						return false;
					}
					break;

				default:
					break;
				}
				return true;
			}
		});
	}

	private void initState() {
		fetcher = new InfraredFetcher(getApplicationContext());
		mState = fetcher.getAirRemoteStatus(remote);
		String t = mState.getTemp().toString();
		String mode = mState.getMode().toString();
		for (int n = 16; n < 33; n++) {
			List<Infrared> irList = fetcher.fetchAirInfrareds(remote, mState, mState.getPower(), mState.getMode(),
					mState.getWind_amount(), AirTemp.getAirTemp(n));
			for (int i = 0; i < irList.size(); i++) {
				if (irList.get(i) != null && irList.get(i).getData() != null) {
					byte[] data = IrDnaSdkHelper.getIrCode(irList.get(i).getFreq(), irList.get(i).getData());
					String str = Util.bytesToHexString(data).toUpperCase();
					String cmd = ConvertUtil.getInstance().convertInfraredCmd(str);
					Log.e("wmy", "空调....###..解析出的红外数据..data = " + cmd);
					cmdMaps.put((10000 + n), cmd);
					irDataMaps.put((10000 + n), str);
					com.dotstone.chipism.bean.Key k = new com.dotstone.chipism.bean.Key();
					k.setKeyNum((10000 + n));
					k.setCodeValue(cmd);
					localKeys.add(k);
					tempKeys.add(k);
				}
			}
			// Log.i("wmy", "irList = " + irList.size());
		}
		if (t.startsWith("T")) {
			t = t.substring(1, t.length());
			temp = Integer.parseInt(t);
			temp1 = temp;
			Message msg = Message.obtain();
			msg.what = 0;
			msg.arg1 = temp;
			if (mode.equals("AUTO")) {
				msg.arg2 = 0;
			} else if (mode.equals("HOT")) {
				msg.arg2 = 1;
			} else if (mode.equals("COLD")) {
				msg.arg2 = 2;
			} else if (mode.equals("DRY")) {
				msg.arg2 = 3;
			}
			mHandler.sendMessage(msg);
		} else {
			// Log.i("wmy", "t = "+t);
			temp = Integer.parseInt(t);
			temp1 = temp;
			Message msg = Message.obtain();
			msg.what = 0;
			msg.arg1 = 26;
			mHandler.sendMessage(msg);
		}
		Log.i("wmy",
				remote.getName() + " mState.getCaculate_number() = " + mState.getCaculate_number()
						+ " mState.getComfort() = " + mState.getComfort() + " mState.getMode() = " + mState.getMode()
						+ " mState.getTemp() = " + mState.getTemp().toString() + " mState.getTemp_display() = "
						+ mState.getTemp_display() + " mState.getWind_hoz() = " + mState.getWind_hoz()
						+ " mState.getWind_ver() = " + mState.getWind_ver() + " mState.getWind_direction() = "
						+ mState.getWind_direction() + " mState.getSleep() = " + mState.getSleep()
						+ " mState.getFlash_air() = " + mState.getFlash_air() + " mState.getHot() = " + mState.getHot()
						+ " mState.getPower_saving() = " + mState.getPower_saving());
	}

	private void initKey() {
		keys = remote.getKeys();
		for (int i = 0; i < keys.size(); i++) {
			Log.i("wmy", "keys.get(i).getLocalName() = " + keys.get(i).getLocalName() + " keys.get(i).getName() = "
					+ keys.get(i).getName());
			List<Infrared> infrareds = null;
			infrareds = new InfraredFetcher(this).fetchInfrareds(remote, keys.get(i));
			if (infrareds != null) {
				for (Infrared ir : infrareds) {
					if (ir != null && ir.getData() != null) {
						// int freq = ir.getFreq();
						// Required ！ 必须调用，此接口将对信号格式进行验证，返回明码信号数据
						// Log.i("wmy", "ir.getData() = "+ir.getData());
						byte[] data = IrDnaSdkHelper.getIrCode(ir.getFreq(), ir.getData());
						// byte[] airData =
						// IrDnaSdkHelper.getAirVMCode(keys.get(i).getProtocol());
						// data格式详见《信号数据格式说明》文档，不同的芯片需要转换成对应的芯片目标码
						// String str = byte2HexStr(data);
						String str = Util.bytesToHexString(data).toUpperCase();
						String cmd = ConvertUtil.getInstance().convertInfraredCmd(str);
						// Log.w("wmy",
						// "send....###..解析出的红外数据..data = "+cmd+" " +
						// Arrays.toString(data));
						// Log.e("wmy", keys.get(i).getType() + " " + cmd);
						cmdMaps.put(keys.get(i).getType(), cmd);
						irDataMaps.put(keys.get(i).getType(), str);
						com.dotstone.chipism.bean.Key k = new com.dotstone.chipism.bean.Key();
						k.setKeyNum(keys.get(i).getType());
						k.setCodeValue(cmd);
						localKeys.add(k);
					}
				}
			}
		}
		initLocalKeys();
	}

	private void initLocalKeys() {
		buttons.clear();
		buttons.add(mModeB);
		buttons.add(mWindB);
		buttons.add(mDerictionB);
		buttons.add(mDerictionB1);
		buttons.add(mWarmB);
		buttons.add(mColdB);
		buttons.add(mTimeB);
		moreKeys.clear();
		// keys = device.getKeys();
		for (int i = 0; i < buttons.size(); i++) {
			// Log.i("wmy",
			// "buttons.get(i).getTag() = "
			// + Integer.parseInt(buttons.get(i).getTag()
			// .toString()));
			String cmd = cmdMaps.get(Integer.parseInt(buttons.get(i).getTag().toString()));
			if (cmd == null) {
				setBg(buttons.get(i).getId(), false);
			} else {
				setBg(buttons.get(i).getId(), true);
			}
		}
		for (int i = 0; i < localKeys.size(); i++) {
			// 如果按键不是温度加和温度减 进行判断
			if (localKeys.get(i).getKeyNum() != 811 && localKeys.get(i).getKeyNum() != 812
					&& localKeys.get(i).getKeyNum() != 800 && localKeys.get(i).getKeyNum() != 4000) {
				boolean e = false;
				for (Button btn : buttons) {

					int tag = Integer.parseInt(btn.getTag().toString());
					if (tag == localKeys.get(i).getKeyNum()) {
						e = true;
						// moreKeys.add(keys.get(i));
						break;
					}
				}
				// if (!e) {
				// moreKeys.add(localKeys.get(i));
				// Log.i("wmy", "添加一个moreKeys"+moreKeys.size());
				// }
				if (!e) {
					boolean e1 = false;
					for (int n = 0; n < moreKeys.size(); n++) {
						if (moreKeys.get(n).getKeyNum() == localKeys.get(i).getKeyNum()) {
							e1 = true;
						}
					}
					if (!e1) {
						// Log.i("wmy", "moreKeys添加 = " +
						// localKeys.get(i).getKeyNum()
						// + " " + i);
						moreKeys.add(localKeys.get(i));
					}
				}
			}
		}
		if (moreKeys.size() > 0) {
			mMoreB.setBackgroundResource(R.drawable.selector_more1);
			// initDialog();
		} else {
			mMoreB.setBackgroundResource(R.drawable.ddd12x);
			mMoreB.setEnabled(false);
		}
	}

	private void setBg(int id, boolean e) {
		if (e) {

			switch (id) {
			case R.id.mode_btn:
				mModeB.setEnabled(true);
				mModeB.setBackgroundResource(R.drawable.selector_mode);
				break;
			case R.id.wind_speed_btn:
				// 833
				mWindB.setEnabled(true);
				mWindB.setBackgroundResource(R.drawable.selector_wind_speed);
				break;
			case R.id.wind_deriction_btn:
				// 834 左右扫风
				mDerictionB.setEnabled(true);
				mDerictionB.setBackgroundResource(R.drawable.selector_deriction);
				break;
			case R.id.wind_deriction_btn1:
				// 835 上下扫风
				mDerictionB1.setEnabled(true);
				mDerictionB1.setBackgroundResource(R.drawable.selector_deriction1);
				break;
			case R.id.warn_btn:
				// 883
				mWarmB.setEnabled(true);
				mWarmB.setBackgroundResource(R.drawable.selector_warm);
				break;
			case R.id.cold_btn:
				// 882
				mColdB.setEnabled(true);
				mColdB.setBackgroundResource(R.drawable.selector_cold);
				break;
			case R.id.time_btn:
				// 876
				mTimeB.setEnabled(true);
				mTimeB.setBackgroundResource(R.drawable.selector_time);
				break;

			default:
				break;
			}
		} else {
			switch (id) {
			case R.id.mode_btn:
				mModeB.setBackgroundResource(R.drawable.moshi1x);
				mModeB.setEnabled(false);
				break;

			case R.id.wind_speed_btn:
				// 833
				mWindB.setBackgroundResource(R.drawable.fengsu1x);
				mWindB.setEnabled(false);
				break;
			case R.id.wind_deriction_btn:
				// 834 左右扫风
				mDerictionB.setBackgroundResource(R.drawable.xiabai12x);
				mDerictionB.setEnabled(false);
				break;
			case R.id.wind_deriction_btn1:
				// 835 上下扫风
				mDerictionB1.setBackgroundResource(R.drawable.shangbai12x);
				mDerictionB1.setEnabled(false);
				break;
			case R.id.warn_btn:
				// 883
				mWarmB.setBackgroundResource(R.drawable.zhire12x);
				mWarmB.setEnabled(false);
				break;
			case R.id.cold_btn:
				// 882
				mColdB.setBackgroundResource(R.drawable.zhileng12x);
				mColdB.setEnabled(false);
				break;
			case R.id.time_btn:
				// 876
				mTimeB.setBackgroundResource(R.drawable.naozhong12x);
				mTimeB.setEnabled(false);
				break;

			default:
				break;
			}
		}
	}

	private void resetButton(boolean e) {
		if (e) {
			initLocalKeys();
		} else {
			for (int i = 0; i < buttons.size(); i++) {
				setBg(buttons.get(i).getId(), false);
			}
			mMoreB.setEnabled(false);
			mMoreB.setBackgroundResource(R.drawable.ddd12x);
		}
	}

	private void setRecall() {
		socket.setRecDataCallBackListener_TempHumity(new RecDataCallBackListener_TempHumity() {

			@Override
			public void onReceiveData(String data) {
				// TODO Auto-generated method stub
				parseData(data);
			}
		});
	}

//	private void initTemp() {
//		socket.sendMqttData(ConvertUtil.getInstance().convertTempCmd());
//	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	/**
	 * 计算以(src_x,src_y)为坐标圆点，建立直角体系，求出(target_x,target_y)坐标与x轴的夹角
	 * 主要是利用反正切函数的知识求出夹角
	 * 
	 * @param src_x
	 * @param src_y
	 * @param target_x
	 * @param target_y
	 * @return
	 */
	float detaDegree(float src_x, float src_y, float target_x, float target_y) {
		float detaX = target_x - src_x;
		float detaY = target_y - src_y;
		double d;
		if (detaX != 0) {
			float tan = Math.abs(detaY / detaX);

			if (detaX > 0) {

				if (detaY >= 0) {
					d = Math.atan(tan);

				} else {
					d = 2 * Math.PI - Math.atan(tan);
				}

			} else {
				if (detaY >= 0) {

					d = Math.PI - Math.atan(tan);
				} else {
					d = Math.PI + Math.atan(tan);
				}
			}

		} else {
			if (detaY > 0) {
				d = Math.PI / 2;
			} else {

				d = -Math.PI / 2;
			}
		}
		return (float) ((d * 180) / Math.PI);
	}

	private void getButtonXY(float degree) {
		tempX1 = (int) (o_x + (150 * dpi / 320 * Math.cos(Math.toRadians(degree))));
		tempY1 = (int) (o_y + (150 * dpi / 320 * Math.sin(Math.toRadians(degree))));
	}

	private void adjustTemp(float degree) {
		if (130 < degree && degree <= 160) {
			if (temp != 16) {
				temp = 16;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd(cmdMaps.get(10016));
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_1);
				mGeImg.setImageResource(R.drawable.ac_6);
				vibrator.vibrate(50);
			} else if (160 < degree && degree <= 177) {
				if (temp != 17) {
					temp = 17;
					if (temp1 > temp) {
						Log.i("wmy", "调低温度");
						// sendCmdThread(false, temp1 - temp);
					} else {
						Log.i("wmy", "调高温度");
						// sendCmdThread(true, temp - temp1);
					}
					sendCmd(cmdMaps.get(10017));
					temp1 = temp;
					mShiImg.setImageResource(R.drawable.ac_1);
					mGeImg.setImageResource(R.drawable.ac_7);
					vibrator.vibrate(50);
				}
			}
		} else if (177 < degree && degree <= 194) {
			if (temp != 18) {
				temp = 18;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd(cmdMaps.get(10018));
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_1);
				mGeImg.setImageResource(R.drawable.ac_8);
				vibrator.vibrate(50);
			}
		} else if (194 < degree && degree <= 211) {
			if (temp != 19) {
				temp = 19;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd(cmdMaps.get(10019));
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_1);
				mGeImg.setImageResource(R.drawable.ac_9);
				vibrator.vibrate(50);
			}
		} else if (211 < degree && degree <= 228) {
			if (temp != 20) {
				temp = 20;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd(cmdMaps.get(10020));
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_0);
				vibrator.vibrate(50);
			}
		} else if (228 < degree && degree <= 245) {
			if (temp != 21) {
				temp = 21;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd(cmdMaps.get(10021));
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_1);
				vibrator.vibrate(50);
			}
		} else if (245 < degree && degree <= 262) {
			if (temp != 22) {
				temp = 22;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd(cmdMaps.get(10022));
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_2);
				vibrator.vibrate(50);
			}
		} else if (262 < degree && degree <= 279) {
			if (temp != 23) {
				temp = 23;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd(cmdMaps.get(10023));
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_3);
				vibrator.vibrate(50);
			}
		} else if (279 < degree && degree <= 296) {
			if (temp != 24) {
				temp = 24;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd(cmdMaps.get(10024));
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_4);
				vibrator.vibrate(50);
			}
		} else if (296 < degree && degree <= 313) {
			if (temp != 25) {
				temp = 25;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd(cmdMaps.get(10025));
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_5);
				vibrator.vibrate(50);
			}
		} else if (313 < degree && degree <= 330) {
			if (temp != 26) {
				temp = 26;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd(cmdMaps.get(10026));
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_6);
				vibrator.vibrate(50);
			}
		} else if (330 < degree && degree <= 347) {
			if (temp != 27) {
				temp = 27;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd(cmdMaps.get(10027));
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_7);
				vibrator.vibrate(50);
			}
		} else if (347 < degree || degree <= 3) {
			if (temp != 28) {
				temp = 28;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd(cmdMaps.get(10028));
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_8);
				vibrator.vibrate(50);
			}
		} else if (3 < degree && degree <= 20) {
			if (temp != 29) {
				temp = 29;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd(cmdMaps.get(10029));
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_9);
				vibrator.vibrate(50);
			}
		} else if (20 < degree && degree <= 50) {
			if (temp != 30) {
				temp = 30;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd(cmdMaps.get(10030));
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_3);
				mGeImg.setImageResource(R.drawable.ac_0);
				vibrator.vibrate(50);
			}
		}
	}

	// private void adjustTemp(float degree) {
	// if (130 < degree && degree <= 180) {
	// if (temp != 16) {
	// temp = 16;
	// if (temp1 > temp) {
	// Log.i("wmy", "调低温度");
	// sendCmdThread(false, temp1 - temp);
	// } else {
	// Log.i("wmy", "调高温度");
	// sendCmdThread(true, temp - temp1);
	// }
	// temp1 = temp;
	// mShiImg.setImageResource(R.drawable.ac_1);
	// mGeImg.setImageResource(R.drawable.ac_6);
	// vibrator.vibrate(50);
	// }
	// } else if (180 < degree && degree <= 210) {
	// if (temp != 18) {
	// temp = 18;
	// if (temp1 > temp) {
	// Log.i("wmy", "调低温度");
	// sendCmdThread(false, temp1 - temp);
	// } else {
	// Log.i("wmy", "调高温度");
	// sendCmdThread(true, temp - temp1);
	// }
	// temp1 = temp;
	// mShiImg.setImageResource(R.drawable.ac_1);
	// mGeImg.setImageResource(R.drawable.ac_8);
	// vibrator.vibrate(50);
	// }
	// } else if (210 < degree && degree <= 240) {
	// if (temp != 20) {
	// temp = 20;
	// if (temp1 > temp) {
	// Log.i("wmy", "调低温度");
	// sendCmdThread(false, temp1 - temp);
	// } else {
	// Log.i("wmy", "调高温度");
	// sendCmdThread(true, temp - temp1);
	// }
	// temp1 = temp;
	// mShiImg.setImageResource(R.drawable.ac_2);
	// mGeImg.setImageResource(R.drawable.ac_0);
	// vibrator.vibrate(50);
	// }
	// } else if (240 < degree && degree <= 270) {
	// if (temp != 22) {
	// temp = 22;
	// if (temp1 > temp) {
	// Log.i("wmy", "调低温度");
	// sendCmdThread(false, temp1 - temp);
	// } else {
	// Log.i("wmy", "调高温度");
	// sendCmdThread(true, temp - temp1);
	// }
	// temp1 = temp;
	// mShiImg.setImageResource(R.drawable.ac_2);
	// mGeImg.setImageResource(R.drawable.ac_2);
	// vibrator.vibrate(50);
	// }
	// } else if (270 < degree && degree <= 300) {
	// if (temp != 24) {
	// temp = 24;
	// if (temp1 > temp) {
	// Log.i("wmy", "调低温度");
	// sendCmdThread(false, temp1 - temp);
	// } else {
	// Log.i("wmy", "调高温度");
	// sendCmdThread(true, temp - temp1);
	// }
	// temp1 = temp;
	// mShiImg.setImageResource(R.drawable.ac_2);
	// mGeImg.setImageResource(R.drawable.ac_4);
	// vibrator.vibrate(50);
	// }
	// } else if (300 < degree && degree <= 330) {
	// if (temp != 26) {
	// temp = 26;
	// if (temp1 > temp) {
	// Log.i("wmy", "调低温度");
	// sendCmdThread(false, temp1 - temp);
	// } else {
	// Log.i("wmy", "调高温度");
	// sendCmdThread(true, temp - temp1);
	// }
	// temp1 = temp;
	// mShiImg.setImageResource(R.drawable.ac_2);
	// mGeImg.setImageResource(R.drawable.ac_6);
	// vibrator.vibrate(50);
	// }
	// } else if (330 < degree && degree <= 360) {
	// if (temp != 28) {
	// temp = 28;
	// if (temp1 > temp) {
	// Log.i("wmy", "调低温度");
	// sendCmdThread(false, temp1 - temp);
	// } else {
	// Log.i("wmy", "调高温度");
	// sendCmdThread(true, temp - temp1);
	// }
	// temp1 = temp;
	// mShiImg.setImageResource(R.drawable.ac_2);
	// mGeImg.setImageResource(R.drawable.ac_8);
	// vibrator.vibrate(50);
	// }
	// } else if (0 < degree && degree <= 50) {
	// if (temp != 30) {
	// temp = 30;
	// if (temp1 > temp) {
	// Log.i("wmy", "调低温度");
	// sendCmdThread(false, temp1 - temp);
	// } else {
	// Log.i("wmy", "调高温度");
	// sendCmdThread(true, temp - temp1);
	// }
	// temp1 = temp;
	// mShiImg.setImageResource(R.drawable.ac_3);
	// mGeImg.setImageResource(R.drawable.ac_0);
	// vibrator.vibrate(50);
	// }
	// }
	// }

	private void parseData(String data) {
		try {
			JSONObject jo = new JSONObject(data);
			String g = jo.getString("g");
			JSONObject jo1 = new JSONObject(g);
			int temperature = (int) jo1.getDouble("temperature");
			Message msg = Message.obtain();
			msg.what = 0;
			msg.arg1 = temperature;
			mHandler.sendMessage(msg);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private boolean adjustArea(float src_x, float src_y, float target_x, float target_y) {
		inner = (int) Math.sqrt(Math.pow(Math.abs(target_x - src_x), 2) + Math.pow(Math.abs(target_y - src_y), 2));
		if (inner < 300 * dpi / 320 && inner > 90 * dpi / 320) {
			return true;
		} else {
			return false;
		}
	}

	// 保存该遥控器
	private void save() {
		mSVProgressHUD = new SVProgressHUD(AddAirActivity.this);
		mSVProgressHUD.showWithStatus("正在保存");
		// 上传设备
		RequestParams params = new RequestParams(HttpURL.UPLOAD_DEVICE_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {

			obj.put("classification", "4");
			obj.put("key", "10000");
			obj.put("deviceModel", remoteId);
			obj.put("deviceName", aplliance + " " + brand + " " + model);
			obj.put("deviceType", type + "");
			obj.put("deviceVersion", "3.1.0");
			obj.put("deviceWifiSSID", remoteId.equals("") ? "未知" : remoteId);
			obj.put("deviceId", "0");
			obj.put("productId", "4");
			obj.put("mainDeviceId", DeviceManager.getInstance().getmWlanId());
			obj.put("hid", DeviceManager.getInstance().hid);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			Log.d("test", " upload obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("test", "upload=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					String value = jsonObject.getString("resultCode");
					if (value.equals("1")) {
						String deviceId = jsonObject.getString("data");
						// 获取deviceId之后 上传所有按键
						uploadKeys(deviceId);
					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), "保存失败：" + errorMsg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void uploadKeys(String deviceId) {
		// 上传按键
		String buttonCmdS = "";
		String positionS = "";
		String nameS = "";
		boolean e = false;
		String cmd = "";
		for (int i = 0; i < keys.size(); i++) {
			if (cmdMaps.get(keys.get(i).getType()) != null) {
				buttonCmdS += irDataMaps.get(keys.get(i).getType()) + ",";
				positionS += keys.get(i).getType() + ",";
				if (keys.get(i).getType() == 800) {
					nameS += "打开" + ",";
					cmd = irDataMaps.get(keys.get(i).getType());
				} else if (keys.get(i).getType() == 4000) {
					e = true;
					nameS += "关闭" + ",";
				} else {
					nameS += keys.get(i).getLocalName() + ",";
				}
			}
		}
		if (!e) {
			buttonCmdS += cmd+",";
			nameS += "关闭" + ",";
			positionS += 4000 + ",";
		}

		for (int i = 0; i < tempKeys.size(); i++) {
			buttonCmdS += irDataMaps.get(tempKeys.get(i).getKeyNum()) + ",";
			positionS += tempKeys.get(i).getKeyNum() + ",";
			nameS += KeyManager.getInstance().getKeyNameById(tempKeys.get(i).getKeyNum()) + ",";
		}
		if (buttonCmdS.length() > 1) {
			buttonCmdS = buttonCmdS.substring(0, buttonCmdS.length() - 1);
		}
		if (positionS.length() > 1) {
			positionS = positionS.substring(0, positionS.length() - 1);
		}
		if (nameS.length() > 1) {
			nameS = nameS.substring(0, nameS.length() - 1);
		}
		RequestParams params = new RequestParams(HttpURL.UPLOAD_REMOTE_KEY_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("buttonCmdS", buttonCmdS);
			obj.put("key", "10000");
			obj.put("positionS", positionS);
			obj.put("nameS", nameS);
			obj.put("deviceId", deviceId);
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			Log.d("test", " upload obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("test", "upload=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					String value = jsonObject.getString("resultCode");
					if (value.equals("1")) {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						ToastShow.Show(getApplicationContext(), "保存成功");
						finish();
					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), "保存失败：" + errorMsg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	// private void sendCmdThread(boolean up, final int count) {
	// if (up) {
	// for (int i = 0; i < count; i++) {
	// Log.i("wmy", "加入对列" + cmdMaps.get(811));
	// socket.sendMqttDataDelay(cmdMaps.get(811));
	// }
	// } else {
	// for (int i = 0; i < count; i++) {
	// Log.i("wmy", "加入对列" + cmdMaps.get(812));
	// socket.sendMqttDataDelay(cmdMaps.get(812));
	// }
	// }
	// }

	private void sendCmd(String cmd) {
		if (cmd == null) {
			return;
		}
		if (socket.isLocalSuccess()) {
			socket.sendMqttData(cmd);
		} else {
			SocketManager.getInstance().sendRemoteData(socket.getMac(), DeviceManager.getInstance().getmWlanId(), cmd);
		}
	}

	class KeyAdapter extends BaseAdapter {
		HoldView holdView;
		private int imageResId;
		private int stringResId;

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return moreKeys.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return moreKeys.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View v, ViewGroup parent) {
			// TODO Auto-generated method stub
			if (v == null) {
				v = LayoutInflater.from(AddAirActivity.this).inflate(R.layout.item_more_key, null);
				holdView = new HoldView();
				holdView.btn = (Button) v.findViewById(R.id.key_btn);
				v.setTag(holdView);
			} else {
				holdView = (HoldView) v.getTag();
			}
			final com.dotstone.chipism.bean.Key k = moreKeys.get(position);
			holdView.btn.setTag(k.getKeyNum());
			int content = KeyManager.getInstance().getContentTypeByKeyNum(k.getKeyNum());
			if (content == 0) {
				imageResId = KeyManager.getInstance().getDrawableResId(k.getKeyNum());
				holdView.btn.setBackgroundResource(imageResId);
			} else {
				stringResId = KeyManager.getInstance().getStringResId(k.getKeyNum());
				holdView.btn.setText(stringResId);
			}
			holdView.btn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Log.i("wmy", "点击了" + k.getKeyNum());
					int tag = Integer.parseInt(v.getTag().toString());
					sendCmd(cmdMaps.get(tag));
					vibrator.vibrate(50);
				}
			});

			return v;
		}
	}

	class HoldView {
		private Button btn;
	}

}
